package multithreading;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //继承Thread类
        //此方式给线程名命可以直接调用父类Thread的方法
        //获取自定义类对象并继承Thread并重写run方法
        ExtendsThread et1 = new ExtendsThread();
        ExtendsThread et2 = new ExtendsThread();
        //调用父类方法给线程名命
        et1.setName("线程1");
        et2.setName("线程2");
        //开启线程
        et1.start();
        et2.start();
        //===============================================================
        //实现Runable类
        /*此种方法如果想要和给线程名命，需要在run方法里用Thread的静态方法currentThread()返回Thread对象
         * 再通过Thread对象调用setName方法给线程名命*/
        //创建自定义类实现Runable并重写run方法
        ImplementsRunable tr1 = new ImplementsRunable();
        ImplementsRunable tr2 = new ImplementsRunable();
        //创建Thread对象并把自定义类传入Thread
        Thread t1 = new Thread(tr1);
        Thread t2 = new Thread(tr2);
        //利用Thread对象调用Thread里的setName方法给线程名命
        t1.setName("实现线程1");
        t2.setName("实现线程2");
        //用Thread对象调用start方法开启线程
        t1.start();
        t2.start();
        //==============================================
        //实现Callable类
        //该方式的特点是可以获取线程执行的结果
        //创建自定义类并实现Callable方法并重写里面的call方法
        ImplementsCallableFuture cf = new ImplementsCallableFuture();
        //创建FutureTask对象并传入自定义对象
        FutureTask<Integer> ft = new FutureTask<>(cf);
        //创建Thread对象并传入FutureTask对象
        Thread thread = new Thread(ft);
        //用Thread对象开启线程
        thread.start();
        //利用FutureTask对象获取线程执行结果
        Integer integer = ft.get();
        //打印线程执行结果
        System.out.println(integer);
    }
}
